package com.milhouz.pokertimer.timers;

import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.Chronometer;

/**
 * http://www.craigethomas.com/blog/2009/06/extending-androids-chronometer-to-get-elapsed-time/
 * @author bpetetot
 */
public class MyChronometer extends Chronometer  {

	public long msElapsed;
	private boolean isRunning = false;

	public MyChronometer(Context context) {
		super(context);
	}
	
	public MyChronometer(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	/* (non-Javadoc)
	 * @see com.milhouz.pokertimer.timers.ITimer#getMsElapsed()
	 */
	public long getMsElapsed() {
		return msElapsed;
	}
	
	/* (non-Javadoc)
	 * @see com.milhouz.pokertimer.timers.ITimer#getSecElapsed()
	 */
	public long getSecElapsed() {
		if (isRunning)
			return (SystemClock.elapsedRealtime() - this.getBase()) / 1000;
		else
			return msElapsed / 1000;
	}

	/* (non-Javadoc)
	 * @see com.milhouz.pokertimer.timers.ITimer#setMsElapsed(long)
	 */
	public void setMsElapsed(long ms) {
		setBase(getBase() - ms);
		msElapsed = ms;
	}
	
	/* (non-Javadoc)
	 * @see com.milhouz.pokertimer.timers.ITimer#setMsElapsed(long, long)
	 */
	public void setMsElapsed(long ms, long chronoBase) {
		setBase(chronoBase - ms);
		msElapsed = ms;
	}

	/* (non-Javadoc)
	 * @see com.milhouz.pokertimer.timers.ITimer#start()
	 */
	@Override
	public void start() {
		super.start();
		setBase(SystemClock.elapsedRealtime() - msElapsed);
		isRunning = true;
	}

	/* (non-Javadoc)
	 * @see com.milhouz.pokertimer.timers.ITimer#stop()
	 */
	@Override
	public void stop() {
		super.stop();
		if (isRunning) {
			msElapsed = (long) (SystemClock.elapsedRealtime() - this.getBase());
			isRunning = false;
		}
	}
	
	/* (non-Javadoc)
	 * @see com.milhouz.pokertimer.timers.ITimer#reset()
	 */
	public void reset() {
		if (isRunning) {
			this.stop();
		}
		this.destroyDrawingCache();
		msElapsed = 0;
		setBase(SystemClock.elapsedRealtime() - msElapsed);
	}

	public boolean isRunning() {
		return isRunning;
	}

	
	
}
